/**
 * Proj1_1 This JavaScript file is for Canvas view.
 */
//constants
// do not change.......plz
PAGE_ID_HOME = 0;
PAGE_ID_FRIENDS = 1;
PAGE_ID_TWITTER = 2;
PAGE_ID_NEWS = 3;
PAGE_ID_ERRORS = 4;

// variables
// to show error messages or to accumulate them in error box
var showAlert = true;
// tab view tab control.
var myTabs;
// limit # friends per page
var limit = 5; // must match min option in pagesize combo
// current page #
var page = 1;
// array of friends to be invited
var arrFriends = [];
// name of viewer, in this app viewer == owner
var viewerName = '';

// array of person objects;
var g_arrPerson = [];

function Proj1_1_init() {
    try {
        // Note: seek here for init() errors
        fetchPeople(page);

        var listOptions = '<select id="pagesize" onchange="showMessage(pagesize.value);limit=pagesize.value;page=1;fetchPeople(page);"> ';
        listOptions += ' <option value="5">5</option> ';
        listOptions += ' <option value="10">10</option>';
        listOptions += ' <option value="25">25</option>';
        listOptions += ' <option value="100">100</option></select>';
        document.getElementById("ddlist").innerHTML = listOptions;

        setupPageControls(PAGE_ID_HOME);
    } catch (err) {
        handleException("[init()] :" + err.description);
    }
}

function fetchPeople(nPage) {
    try {
    	// clear array
    	g_arrPerson = [];
        // Note: seek here for fetchPeople() errors
        // calculate start # based on page number passed.
        var myStart = parseInt((nPage - 1) * limit, 10);
        var req = opensocial.newDataRequest();
        req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
        // id specification
        var params = {};
        params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER;
        params[opensocial.IdSpec.Field.GROUP_ID] = 'FRIENDS';
        var idSpec = opensocial.newIdSpec(params);
        // options
        var opt_param = {};
        opt_param[opensocial.DataRequest.PeopleRequestFields.FIRST] = myStart;
        opt_param[opensocial.DataRequest.PeopleRequestFields.MAX] = limit;
        req.add(req.newFetchPeopleRequest(idSpec, opt_param), 'friends');
        // send request with an handler
        req.send(onLoadResponse);
    } catch (err) {
        handleException("[fetchPeople()] :" + err.description);
    }
}

/*
 * getFriendDetails() - queries container for person details.
 * id = id for the person
 */
function getFriendDetails(idx){
	try{
        // navigate to page 2
        navigateTab(PAGE_ID_FRIENDS);

		var person = g_arrPerson[idx];
		var name = person.getDisplayName();
		//1. get photo
        var profileThumbnail = person.getField(opensocial.Person.Field.THUMBNAIL_URL);
		//2. get URL
        var profilePage = person.getField(opensocial.Person.Field.PROFILE_URL);

        // set photo
        var text = "<a href=\""+profilePage +"\" target=\"_parent\" >"; 
        text += "<img border=\"0\" src=\""+profileThumbnail+"\" title=\""+name+"\" alt=\""+name+"\" height=\"100px\" width=\"100px\"/> </a>";
        document.getElementById("friendsPhoto").innerHTML = text;
        
        //3. get status
        var status = person.getField(opensocial.Person.Field.STATUS);
        //4. get about me
        var About = person.getField(opensocial.Person.Field.ABOUT_ME);
        text =  "<ul> <li> Status: <em>"+status+"</em> </li>";
        text += "<li> About: "+About+"</li>";
        document.getElementById("friendsInfo").innerHTML = text;
        
        // get some more information.
        /*
         * ADDRESSES
         * CURRENT_LOCATION
         * FOOD
         * FASHION
         * HUMOR
         * INTERESTS
         */
        text ="<li> Location: <i>"+person.getField(opensocial.Person.Field.CURRENT_LOCATION)+"</i></li>";
        text +="<li> Pets: <i>"+person.getField(opensocial.Person.Field.PETS)+"</i></li>";
        text +="<li> Fashion: <i>"+person.getField(opensocial.Person.Field.FASHION)+"</i></li>";
        text +="<li> Humor: <i>"+person.getField(opensocial.Person.Field.HUMOR)+"</i></li>";
        text +="<li> Interests: <i>"+person.getField(opensocial.Person.Field.INTERESTS)+"</i></li>";
        text +="<li> EMAILS: <i>"+person.getField(opensocial.Person.Field.EMAILS)+"</i></li>";
        
        document.getElementById("friendsDetails").innerHTML = text;
        
	}catch (err){
		// in case of err, navigate  to ERROR page
		navigateTab(PAGE_ID_ERRORS);
		handleException("[getFriendDetails()]" + err.description);
	}
	gadgets.window.adjustHeight();
}


function onLoadResponse(data) {
    try {
        // seek here for .*[friendsHTML].* errors
        // get viewer object
        var viewer = data.get('viewer').getData();
        // show viewer name
        viewerName = viewer.getDisplayName();
        document.getElementById("viewer").innerHTML = 'Hello, ' + viewerName + ', your friends are,';
        // get friends data
        var friends = data.get('friends').getData();
        document.getElementById("viewerfriends").innerHTML = '';

        var localcount = 0;
        var inviteControls = '';

        var friends_html = '';

        friends_html += '<table border="0" cellpadding="1" cellspacing="1" width="100%">';
        friends.each(function (person) {
        	// add this into temp array
        	g_arrPerson.push(person);
            var name = person.getDisplayName();

            var friendDetails = "";
            friendDetails += "<tr width=\"100%\">";
            friendDetails += "<td align=\"left\" class=\"yui-content\"> ";
            //friendDetails += "<a href=\"javascript:void();\" onclick=\"getFriendDetails("+person+");\">";
            friendDetails += "<a href=\"javascript:void();\" onclick=\"getFriendDetails("+localcount+");\">";
            friendDetails += name;
            friendDetails += "</a></td> </tr>";

            friends_html += friendDetails;
            // / maintain a local count to decide
            localcount++;
        });
        friends_html = friends_html + '</table>';
    } catch (err) {
        handleException("[onLoadResponse()] [friendsHTML]:" + err.description);
    }

    // setup pages
    setupPageControls(localcount);

    try {
        // / Note: seek here for .*[innerHTML].* exceptions
        document.getElementById("viewerfriends").innerHTML = friends_html;
    } catch (err) {
        handleException("[onLoadResponse()] [innerHTML]:" + err.description);
    }
    gadgets.window.adjustHeight();
}

/*
 * given count of #of people, it creates pagination controls.
 */
function setupPageControls(Count) {
    try {
        // Note: seek here for pageControls errors
        var pageControls = '';
        if (page != 1) {
            // show back button only when start != 0
            pageControls += '<input type=\"button\" class=\"yui-button yui-push-button\" onClick=\'page=page-1;fetchPeople(page);\' value=\'<\' /> ';
        } else {
            pageControls += '<input type=\"button\" class=\"yui-button yui-push-button\" disabled value=\'<\' /> ';
        }

        pageControls += 'Page [' + page + ']  ';

        if (Count == limit) {
            // if count matches, show next control
            // Problem: may show an extra button when pagination is exact
            pageControls += "<input type=\"button\" class=\"yui-button yui-push-button\" onClick=\"page=page+1;fetchPeople(page);\" value=\">\" /> ";
        } else {
            pageControls += "<input type=\"button\" class=\"yui-button yui-push-button\" disabled value=\">\" /> ";
        }
        document.getElementById("pageCtrl").innerHTML = pageControls;

    } catch (err) {
        handleException("[onLoadResponse()] [pageControls]:" + err.description);
    }
}

// this function will append current error text to error section
// err = string object
function handleException(err) {
    if (showAlert) {
        alert(err);
    }
    document.getElementById("errors").innerHTML += "<br/>" + err;
    gadgets.window.adjustHeight();
}

// this function will show alert message based on settings else bypass it.
// err = string object


function showMessage(err) {
    if (showAlert) {
        alert(err);
    }
}

function navigateTab(id){
	try{
	myTabs.set('activeIndex', id);
	}catch (ex){
		handleException("[navigateTab()]" + ex);
	}
}